package net.cnki.sunny.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.cnki.sunny.annotation.OperateLog;
import net.cnki.sunny.common.ResultVO;
import net.cnki.sunny.model.enums.OperateLogEnums;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class SecurityAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    @OperateLog(operateType = OperateLogEnums.OperateType.OPERATE_LOGIN)
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        PrintWriter out = httpServletResponse.getWriter();
        out.write(new ObjectMapper().writeValueAsString(new ResultVO().success(SecurityContextHolder.getContext().getAuthentication().getName())));
    }
}
